package domain

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)
// 数据库相关操作

/*
	功能：
		1. 从存储中取出APPID和对应密码
	注意：数据存储方式有多种 可以mysql redis zookeeper等 则这个设计成接口
 */

type CredentialStorage interface {
	// 从数据库或其他中根据appID取出密码 用于之后的组成token
	GetPasswordByAppId(appId string) string
}

type MongodbCredentialStorage struct {

}

var (

	client     *mongo.Client
	err error

)
func NewMongodbCredentialStorage()*MongodbCredentialStorage{
	return &MongodbCredentialStorage{

	}
}
func InitMongoDB(){

	//连接
	if client, err = mongo.Connect(context.TODO(), options.Client().ApplyURI("mongodb://localhost:27017").SetConnectTimeout(5*time.Second)); err != nil {
		fmt.Print(err)
		return
	}
}

// 单个插入
func (this *MongodbCredentialStorage)InsertOne(val interface{}) (){
	database := client.Database("testdb")
	auth := database.Collection("token")
	_, err = auth.InsertOne(context.Background(), val)
	//fmt.Println("插入完成")
	if err !=nil{
		fmt.Println("插入err=",err)
	}
}

func (this *MongodbCredentialStorage)GetPasswordByAppId(appId string) string{
	database := client.Database("testdb")
	auth := database.Collection("token")
	data:=Auth{}
	err = auth.FindOne(context.Background(), bson.D{{"appId", appId}}.Map()).Decode(&data)
	if err!=nil{
		fmt.Println("err=",err)
	}
	return data.Password
}

type Auth struct {
	AppId string	`bson:"appId"`
	Password string	`bson:"password"`
}